package com.itheima.reggie.web;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/order")
@Slf4j
public class OrdersController {
    @Autowired
    IShoppingCartService shoppingCartService;
    @Autowired
    IUserService userService;
    @Autowired
    IAddressBookService addressBookService;
    @Autowired
    IOdersService odersService;
    @Autowired
    IOderDetailService oderDetailService;

    /**
     * 将当前购物车中的列表数据,储存到两张表中
     *  shoppingCart中的数据储存到order_detail表中
     *      1.shoppingCart中几件商品--储存到---order_detail形成三个订单明细
     *      2.根据购物车中的商品信息,生成订单数据,储存到order数据表中
     *      3.清空购物车中的数据shoppingCart
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        //生成订单的业务流程
        //1.获得当前用户id
        Long userId = BaseContext.getCurrentId();
        //2.查询购物车数据：select * from shopping_cart where user_id = ?
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(queryWrapper);
        if (shoppingCarts == null || shoppingCarts.size() ==0){
            throw new CustomException("购物车为空，不能下单");
        }
        //3.查询地址信息
        //根据地址id查询地址数据 select * from address_book where id = ?
        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if (addressBook==null){
            throw new CustomException("用户地址信息有误，不能下单");
        }
        //4.生成订单号
        long orderId = IdWorker.getId();
        //5.获取用户信息
        User user = userService.getById(userId);
        //计算总金额:保证我们每一次执行的累加计算
        AtomicInteger amount = new AtomicInteger(0);
        //6.封装订单项明细信息
        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());
        //7.组装订单数据
        orders.setId(orderId);//订单Id
        orders.setOrderTime(LocalDateTime.now());//订单创建时间
        orders.setCheckoutTime(LocalDateTime.now());//订单结账时间
        orders.setStatus(2);//1待付款，2待派送，3已派送，4已完成，5已取消
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userId);//用户id
        orders.setNumber(String.valueOf(orderId));//订单号
        orders.setUserName(user.getName());//用户名
        orders.setConsignee(addressBook.getConsignee());//收货人
        orders.setPhone(addressBook.getPhone());//收货人联系电话
        orders.setAddress(
                        (addressBook.getProvinceName()== null?"":addressBook.getProvinceName())
                        +(addressBook.getCityName()==null?"":addressBook.getCityName())
                        + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                        + (addressBook.getDetail() == null ? "" : addressBook.getDetail()) //省+市+区域+详细地址
        );
        odersService.save(orders);
        oderDetailService.saveBatch(orderDetails);
        //8清空购物车
        shoppingCartService.remove(queryWrapper);
        return R.success("清空购物车成功");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> page(Integer page , Integer pageSize){
        //分页构造器对象
        Page<Orders> ordersPage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getUserId,BaseContext.getCurrentId());

        odersService.page(ordersPage,queryWrapper);

        return R.success(ordersPage);


    }

}
